package com.common.spring;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.common.config.ConfigException;

/**
 * Comment of OtterServiceLocator
 * 
 * @author
 * @author 重写 customizeBeanFactory，防止重复id
 */
public class SpringContextLocator {

	private static ApplicationContext context = null;
	private static String DEFAULT_SPRING = "spring/applicationContext.xml";

	public static void setConfig(String config) {
			DEFAULT_SPRING = config;
	}

	private static ApplicationContext getApplicationContext(String config) {

		if (context == null) {
			synchronized (SpringContextLocator.class) {
				if (context == null) {
					try {

						context = new ClassPathXmlApplicationContext(config) {

							@Override
							protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
										super.customizeBeanFactory(beanFactory);
										beanFactory.setAllowBeanDefinitionOverriding(false);
							}
						};
					} catch (RuntimeException e) {
						throw new ConfigException("ERROR ## ", e);
					}
				}

			}
		}

		return context;
	}

	public static void close() {
		((ClassPathXmlApplicationContext) context).close();
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		return (T) getApplicationContext(DEFAULT_SPRING).getBean(name);
	}

	/**
	 * 根据当前spring容器的bean定义，解析对应的object并完成注入
	 */
	public static void autowire(Object obj) {
		// 重新注入一下对象
		context.getAutowireCapableBeanFactory().autowireBeanProperties(obj,
				AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
	}

}
